import pygame
import sys
import random

from pygame.locals import Rect, K_LEFT, K_RIGHT, KEYDOWN, K_UP, K_DOWN, K_SPACE


pygame.init()
pygame.display.set_caption("ROBO抽奖")
icon = pygame.image.load("images/抽奖.gif")
pygame.display.set_icon(icon)
WIDTH = 650
HEIGHT = 550
FPS = 50
clock = pygame.time.Clock()


class Game:
    def __init__(self):
        self.width = WIDTH
        self.height = HEIGHT
        self.window = pygame.display.set_mode((self.width, self.height))
        self.red = (255, 0, 0)
        self.green = (0, 255, 0)
        self.blue = (0, 0, 255)
        self.white = (255, 255, 255)
        self.black = (0, 0, 0)
        self.orange = (255, 128, 0)
        self.student_imgdict = {
            "世欧": ['宋昱辰', '习昊宇', '杨轩瑞', '郑诗涵'],
            "东6": ['林永淳', '黄乐濯', '郑俊爔', '肖卓航', '桂语桐', '易以劭', '薛皓天', '李玥菡'],
            "五四": ['朱良坤', '林熙涵', '沈林希', '雷弘毅', '田正浩', '李绍轩', '高靖远'],
            "群升": ['张闳尧', '方言臻', '曹仲睿', '张希正', '陈子扬'],
            "明腾": ['陈科成', '周子揆', '王堇硕', '陈宇宝', '蔡思齐', '梁梓桐'],
            "东5": ['廖宸帆', "陈予安", "高逸轩", "柯泓宇", "王泽宇"],
        }
        self.bg = Image("bg3", [0, 0], WIDTH, HEIGHT)
        self.imagegroup = pygame.sprite.Group()
        self.chooselist = list(self.student_imgdict.keys())
        self.change = 0
        self.choose = self.chooselist[self.change]
        self.listxy = [
            [20, 20], [20, 200], [20, 380], [200, 20], [200, 200], [200, 380],
            [380, 20], [380, 200], [380, 380]
        ]
        self.points = [[1, 1], [WIDTH - 1, 1], [WIDTH - 1, HEIGHT - 1], [1, HEIGHT - 1]]
        self.btn1 = [560, 20, 80, 35]  # 按钮坐标x, y, w, h
        self.btn2 = [560, 80, 80, 30]
        self.btn3 = [560, 140, 80, 30]  # 停止
        self.btn4 = [560, 200, 80, 30]  # 抖动
        self.index = 0
        self.isalive = False
        self.shua = True  # 左右按键空则校区
        self.fair = False  # 公平模式，由上下按键控制
        self.last = 0
        self.dou = 0
        self.douword = "有惊喜"
        self.isplaymusic = True

    def key_press_event(self, event):
        """键盘事件"""
        if event.key == K_RIGHT:  # 小键盘 或者键盘上下左右键进行操作移动
            self.change += 1
            self.shua = True
        if event.key == K_LEFT:  # 小键盘 或者键盘上下左右键进行操作移动
            self.change -= 1
            self.shua = True
        if event.key == K_UP:
            self.fair = True
        if event.key == K_DOWN:
            self.fair = False
        if event.key == K_SPACE:
            if self.isplaymusic:
                self.music.stop()
                self.isplaymusic = False
            else:
                self.music.play()
                self.isplaymusic = True
        if self.change >= 5:
            self.change = 0
        if self.change < 0:
            self.change = 5

    def write_font(self, size, txt, color, x, y):
        """写文字
        参数:
        size -- 字体大小
        txt -- 要显示的文本内容
        color -- 文本颜色
        x, y -- 文本在窗口中的位置坐标
        """
        font_name = pygame.font.match_font('fangsong')
        font = pygame.font.Font(font_name, size)  # 字体
        font = font.render(txt, True, color)  # 显示字体
        rect = font.get_rect()  # 获得矩形对象

        rect.x, rect.y = x, y  # 设置位置
        self.window.blit(font, rect)  # 刷新添加

    def draw_rect(self):
        pygame.draw.rect(
            self.window, self.green,
            Rect(self.listxy[self.index][0] - 3, self.listxy[self.index][1] - 3, 157, 157), 20
        )

    def draw_lines(self):
        pygame.draw.lines(
            self.window, [200, random.randint(100, 255), random.randint(1, 255)], 1, self.points, 3
        )

    def add_img(self):
        random.shuffle(self.student_imgdict[self.choose])
        self.length = len(self.student_imgdict[self.choose])
        self.trueindexlist = []
        self.imagegroup.empty()
        for x in range(3):
            for y in range(3):
                if self.fair:
                    t = (x * 3 + y) % self.length
                    img = Image(self.student_imgdict[self.choose][t], self.listxy[x * 3 + y], 150, 150, self.dou)
                else:
                    t = random.randint(0, self.length - 1)
                    img = Image(self.student_imgdict[self.choose][t], self.listxy[x * 3 + y], 150, 150, self.dou)
                self.imagegroup.add(img)
                self.trueindexlist.append(t)

    def play_music(self, name):
        """ 播放音乐"""
        self.music = pygame.mixer.music  # 创建音乐播放器
        self.music.load("audios/" + name)  # 加载音乐
        self.music.play()  # 播放音乐

    def run(self):
        self.add_img()
        self.play_music("bg.mp3")
        while True:
            self.window.blit(self.bg.image, [0, 0])
            update_button = Button(self.window, "刷新", self.btn1, "LightBLue", "cyan")
            start_button = Button(self.window, "开始", self.btn2, "LightBLue", "cyan")
            stop_button = Button(self.window, "停止", self.btn3, "LightBLue", "cyan")
            dou_button = Button(self.window, self.douword, self.btn4, "LightBLue", "cyan")
            self.choose = self.chooselist[self.change]
            self.tt = self.trueindexlist[self.index]

            if not self.isalive:
                self.index = self.last

            else:  # 开始滚动
                self.last = self.index
                self.index = random.randint(0, 8)

            if not self.shua:
                self.draw_rect()
                self.draw_lines()
                self.write_font(40, self.student_imgdict[self.choose][self.tt], self.blue, 530, 320)
            else:
                self.write_font(40, "幸运儿？", self.blue, 530, 280)

            self.write_font(28, "<-" + self.choose + "->", self.white, 530, 500)
            self.imagegroup.update()
            self.imagegroup.draw(self.window)
            clock.tick(FPS)

            pygame.display.update()
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
                if event.type == KEYDOWN:
                    self.key_press_event(event)  # 键盘事件
                if event.type == pygame.MOUSEBUTTONDOWN:  # 鼠标按下
                    x, y = pygame.mouse.get_pos()
                    if self.btn1[0] + self.btn1[2] > x > self.btn1[0]:  # 刷新学生
                        if self.btn1[1] + self.btn1[3] > y > self.btn1[1]:
                            self.add_img()
                            self.shua = True
                            self.play_music("bg.mp3")
                    if self.btn2[0] + self.btn2[2] > x > self.btn2[0]:  # 开始
                        if self.btn2[1] + self.btn2[3] > y > self.btn2[1]:
                            self.isalive = True
                            self.shua = False
                            self.play_music("begin.mp3")

                    if self.btn3[0] + self.btn3[2] > x > self.btn3[0]:  # 停止
                        if self.btn3[1] + self.btn3[3] > y > self.btn3[1]:
                            self.isalive = False
                            self.shua = False
                            self.play_music("success.mp3")

                    if self.btn4[0] + self.btn4[2] > x > self.btn4[0]:  # 抖动
                        if self.btn4[1] + self.btn4[3] > y > self.btn4[1]:
                            if self.dou == 1:
                                self.dou = 0
                                self.douword = "有惊喜"
                            else:
                                self.douword = "正在抖动"
                                self.dou = 1
                                self.play_music("move.mp3")
                            for img in self.imagegroup:
                                img.dou = self.dou
                                img.update()


class Button:
    def __init__(self, window, txt, pos, ic, ac):
        self.window = window
        self.mouse = pygame.mouse.get_pos()
        if pos[0] + pos[2] > self.mouse[0] > pos[0] and pos[1] + pos[3] > self.mouse[1] > pos[1]:
            pygame.draw.rect(self.window, ac, pos)
        else:
            pygame.draw.rect(self.window, ic, pos)
        self.txt = txt
        self.small_text = pygame.font.Font('STXINGKA.TTF', 20)
        self.text_surf = self.small_text.render(self.txt, True, [0, 0, 0])
        self.text_rect = self.text_surf.get_rect()
        self.text_rect.center = ((pos[0] + (pos[2] / 2)), (pos[1] + (pos[3] / 2)))
        self.window.blit(self.text_surf, self.text_rect)

    def update(self, txt):
        self.txt = txt
        self.window.blit(self.text_surf, self.text_rect)


class Image(pygame.sprite.Sprite):
    def __init__(self, name, xy, w, h, dou=0):
        pygame.sprite.Sprite.__init__(self)
        self.image1 = pygame.image.load("images/" + name + ".png").convert()
        self.image1 = pygame.transform.scale(self.image1, (w, h))
        self.image1.set_colorkey([0, 255, 255])
        self.image = self.image1
        self.rect = self.image1.get_rect()
        self.rect.x = xy[0]
        self.rect.y = xy[1]
        self.angle = -4
        self.dou = dou

    def update(self):
        if self.dou == 1:
            self.image = pygame.transform.rotate(self.image1, self.angle)
            self.angle += 2
            if self.angle > 4:
                self.angle = -4


if __name__ == "__main__":
    game = Game()
    game.run()
